package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.PersonTrailAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Person;
import com.hengxinguotong.zhihuichengjian.bean.PersonRes;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @CopyRight 恒信国通信息科技
 * @Author wulei
 * @Date 2018/3/14
 * 人员轨迹列表页面
 */

public class PersonTrailListActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_p)
    ImageView ivP;
    @BindView(R.id.et_project)
    HXEditTextView etProject;
    @BindView(R.id.personnel_lv)
    PullToRefreshListView personnelLv;
    private static final int MSG_UPDATE_INFO = 0x110;
    @BindView(R.id.add)
    HXTextView add;
    private int pageIndex = 1;

    private PersonTrailAdapter mPersonTrailAdapter;
    private List<Person> mUsers;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_INFO:
                    if (personnelLv != null) {
                        pageIndex = 1;
                        getPersonnTrailList(null);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personnellist);
        ButterKnife.bind(this);
        tvTitleName.setText("人员轨迹");
        personnelLv.setMode(PullToRefreshBase.Mode.BOTH);
        setLisenter();
//        if(hasAdd()){
//            add.setVisibility(View.VISIBLE);
//        }
        getPersonnTrailList("加载中...");
    }

    private void setLisenter() {
        ivBack.setOnClickListener(this);
        add.setOnClickListener(this);
        personnelLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(PersonTrailListActivity.this, PersonTrailActivity.class);
                intent.putExtra("personName", mUsers.get(position - 1).getName());
                intent.putExtra("personId", mUsers.get(position - 1).getPersonId());
                startActivityForResult(intent, 1);
            }
        });


        personnelLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getPersonnTrailList(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getPersonnTrailList(null);
            }
        });

        etProject.addTextChangedListener(searchTextWatcher);

    }

    private TextWatcher searchTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mHandler.removeMessages(MSG_UPDATE_INFO);
            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 500);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    private void getPersonnTrailList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId",  SPUtil.getString(this,"constructionid"));
            jsonObject.put("name", etProject.getEditableText().toString());
            jsonObject.put("pageNum", pageIndex + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/person/listPerson/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (personnelLv.isRefreshing()) {
                    personnelLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    PersonRes personRes = gson.fromJson(json, PersonRes.class);
                    if(personRes.getStatus() == 1){
                        addData(personRes.getValue());
                    }else {
                        showToast(personRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if (personnelLv.isRefreshing()) {
                    personnelLv.onRefreshComplete();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1 && requestCode == 1) {
            mHandler.removeMessages(MSG_UPDATE_INFO);
            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 500);
        }
    }

    private void addData(List<Person> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(personnelLv);
            }else{
                dismissEmptyView();
            }
            mUsers = datas;
            mPersonTrailAdapter = new PersonTrailAdapter(mUsers, this);
            personnelLv.setAdapter(mPersonTrailAdapter);
            mPersonTrailAdapter.notifyDataSetChanged();
            if (datas.size() == Utils.ONCECOUNT) {
                personnelLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            mUsers.addAll(datas);
            mPersonTrailAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            personnelLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        Intent intent = new Intent();
        switch (id) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.add:
//                ActivityJumper.toAddPersonnelActivity(AddPersonnelActivity.ADDTYPE, PersonTrailActivity.this, null);
                break;
        }

    }
}
